home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 17 / CU Amiga Magazine's Super CD-ROM 17 (1997)(EMAP Images)(GB)[!][issue 1997-12].iso / CUCD / Programming / DiceSource / src / patch / patch.c < prev    next >
C/C++ Source or Header  |  1997-09-09  |  21KB  |  884 lines

  1. /*
  2.  *    (c)Copyright 1992-1997 Obvious Implementations Corp.  Redistribution and
  3.  *    use is allowed under the terms of the DICE-LICENSE FILE,
  4.  *    DICE-LICENSE.TXT.
  5.  */
  6. char rcsid[] =
  7.     "$Header: /home/dice/com/src/patch/RCS/patch.c,v 30.8 1994/08/18 05:51:56 dice Exp dice $";
  8.  
  9. /* patch - a program to apply diffs to original files
  10.  *
  11.  * Copyright 1986, Larry Wall
  12.  *
  13.  * This program may be copied as long as you don't try to make any
  14.  * money off of it, or pretend that you wrote it.
  15.  *
  16.  * $Log: patch.c,v $
  17.  * Revision 30.8  1994/08/18  05:51:56  dice
  18.  * .
  19.  *
  20.  * Revision 30.0  1994/06/10  18:08:50  dice
  21.  * .
  22.  *
  23.  * Revision 30.0  1994/06/10  18:08:50  dice
  24.  * .
  25.  *
  26.  * Revision 2.0.2.0  90/05/01  22:17:50  davison
  27.  * patch12u: unidiff support added
  28.  *
  29.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  30.  * patch12: rindex() wasn't declared
  31.  *
  32.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  33.  * patch10: exit code improved.
  34.  * patch10: better support for non-flexfilenames.
  35.  *
  36.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  37.  * Short replacement caused spurious "Out of sync" message.
  38.  *
  39.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  40.  * Improved diagnostic on sync error.
  41.  * Moved do_ed_script() to pch.c.
  42.  *
  43.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  44.  * Fuzz factor caused offset of installed lines.
  45.  *
  46.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  47.  * Backwards search could terminate prematurely.
  48.  *
  49.  * Revision 2.0  86/09/17  15:37:32  lwall
  50.  * Baseline for netwide release.
  51.  *
  52.  * Revision 1.5  86/08/01  20:53:24  lwall
  53.  * Changed some %d's to %ld's.
  54.  * Linted.
  55.  *
  56.  * Revision 1.4  86/08/01  19:17:29  lwall
  57.  * Fixes for machines that can't vararg.
  58.  * Added fuzz factor.
  59.  * Generalized -p.
  60.  * General cleanup.
  61.  *
  62.  * 85/08/15 van%ucbmonet@berkeley
  63.  * Changes for 4.3bsd diff -c.
  64.  *
  65.  * Revision 1.3  85/03/26  15:07:43  lwall
  66.  * Frozen.
  67.  *
  68.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  69.  * Changed pfp->_file to fileno(pfp).
  70.  *
  71.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  72.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  73.  * Also allow ed output to be suppressed.
  74.  *
  75.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  76.  * Added -p option from jromine@uci-750a.
  77.  *
  78.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  79.  * Now checks for normalness of file to patch.
  80.  *
  81.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  82.  * Added -D (#ifdef) option from joe@fluke.
  83.  *
  84.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  85.  * Made smarter about SCCS subdirectories.
  86.  *
  87.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  88.  * Added -l switch to do loose string comparison.
  89.  *
  90.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  91.  * Failed hunk count not reset on multiple patch file.
  92.  *
  93.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  94.  * Branch for sdcrdcf changes.
  95.  *
  96.  * Revision 1.2  84/11/29  13:29:51  lwall
  97.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  98.  * multiple calls to mktemp().  Will now work on machines that can only
  99.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  100.  * Various cosmetic changes.
  101.  *
  102.  * Revision 1.1  84/11/09  17:03:58  lwall
  103.  * Initial revision
  104.  *
  105.  */
  106.  
  107. #include "INTERN.h"
  108. #include "common.h"
  109. #include "EXTERN.h"
  110. #include "version.h"
  111. #include "util.h"
  112. #include "pch.h"
  113. #include "inp.h"
  114.  
  115. /* procedures */
  116.  
  117. void reinitialize_almost_everything();
  118. void get_some_switches();
  119. LINENUM locate_hunk();
  120. void abort_hunk();
  121. void apply_hunk();
  122. void init_output();
  123. void init_reject();
  124. void copy_till();
  125. void spew_output();
  126. void dump_line();
  127. bool patch_match();
  128. bool similar();
  129. void re_input();
  130. void my_exit();
  131.  
  132. /* Nonzero if -R was specified on command line.  */
  133. static int reverse_flag_specified = FALSE;
  134.  
  135. /* Apply a set of diffs as appropriate. */
  136.  
  137. main(argc,argv)
  138. int argc;
  139. char **argv;
  140. {
  141.     LINENUM where;
  142.     LINENUM newwhere;
  143.     LINENUM fuzz;
  144.     LINENUM mymaxfuzz;
  145.     int hunk = 0;
  146.     int failed = 0;
  147.     int failtotal = 0;
  148.     int i;
  149.  
  150.     setbuf(stderr, serrbuf);
  151.     for (i = 0; i<MAXFILEC; i++)
  152.     filearg[i] = Nullch;
  153.  
  154.     /* Cons up the names of the temporary files.  */
  155.     {
  156.       /* Directory for temporary files.  */
  157.       char *tmpdir;
  158.       int tmpname_len;
  159.  
  160.       tmpdir = getenv ("TMPDIR");
  161.       if (tmpdir == NULL) {
  162.     tmpdir = "/tmp";
  163.       }
  164.       tmpname_len = strlen (tmpdir) + 20;
  165.  
  166.       TMPOUTNAME = (char *) malloc (tmpname_len);
  167.       strcpy (TMPOUTNAME, tmpdir);
  168.       strcat (TMPOUTNAME, "/patchoXXXXXX");
  169.       Mktemp(TMPOUTNAME);
  170.  
  171.       TMPINNAME = (char *) malloc (tmpname_len);
  172.       strcpy (TMPINNAME, tmpdir);
  173.       strcat (TMPINNAME, "/patchiXXXXXX");
  174.       Mktemp(TMPINNAME);
  175.  
  176.       TMPREJNAME = (char *) malloc (tmpname_len);
  177.       strcpy (TMPREJNAME, tmpdir);
  178.       strcat (TMPREJNAME, "/patchrXXXXXX");
  179.       Mktemp(TMPREJNAME);
  180.  
  181.       TMPPATNAME = (char *) malloc (tmpname_len);
  182.       strcpy (TMPPATNAME, tmpdir);
  183.       strcat (TMPPATNAME, "/patchpXXXXXX");
  184.       Mktemp(TMPPATNAME);
  185.     }
  186.  
  187.     /* parse switches */
  188.     Argc = argc;
  189.     Argv = argv;
  190.     get_some_switches();
  191.  
  192.     /* make sure we clean up /tmp in case of disaster */
  193.     set_signals(0);
  194.  
  195.     for (
  196.     open_patch_file(filearg[1]);
  197.     there_is_another_patch();
  198.     reinitialize_almost_everything()
  199.     ) {                 /* for each patch in patch file */
  200.  
  201.     if (outname == Nullch)
  202.         outname = savestr(filearg[0]);
  203.  
  204.     /* initialize the patched file */
  205.     if (!skip_rest_of_patch)
  206.         init_output(TMPOUTNAME);
  207.  
  208.     /* for ed script just up and do it and exit */
  209.     if (diff_type == ED_DIFF) {
  210.         do_ed_script();
  211.         continue;
  212.     }
  213.  
  214.     /* initialize reject file */
  215.     init_reject(TMPREJNAME);
  216.  
  217.     /* find out where all the lines are */
  218.     if (!skip_rest_of_patch)
  219.         scan_input(filearg[0]);
  220.  
  221.     /* from here on, open no standard i/o files, because malloc */
  222.     /* might misfire and we can't catch it easily */
  223.  
  224.     /* apply each hunk of patch */
  225.     hunk = 0;
  226.     failed = 0;
  227.     out_of_mem = FALSE;
  228.     while (another_hunk()) {
  229.         hunk++;
  230.         fuzz = Nulline;
  231.         mymaxfuzz = pch_context();
  232.         if (maxfuzz < mymaxfuzz)
  233.         mymaxfuzz = maxfuzz;
  234.         if (!skip_rest_of_patch) {
  235.         do {
  236.             where = locate_hunk(fuzz);
  237.             if (hunk == 1 && where == Nulline && !force) {
  238.                         /* dwim for reversed patch? */
  239.             if (!pch_swap()) {
  240.                 if (fuzz == Nulline)
  241.                 say1(
  242. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  243.                 continue;
  244.             }
  245.             reverse = !reverse;
  246.             where = locate_hunk(fuzz);  /* try again */
  247.             if (where == Nulline) {     /* didn't find it swapped */
  248.                 if (!pch_swap())         /* put it back to normal */
  249.                 fatal1("Lost hunk on alloc error!\n");
  250.                 reverse = !reverse;
  251.             }
  252.             else if (noreverse) {
  253.                 if (!pch_swap())         /* put it back to normal */
  254.                 fatal1("Lost hunk on alloc error!\n");
  255.                 reverse = !reverse;
  256.                 say1(
  257. "Ignoring previously applied (or reversed) patch.\n");
  258.                 skip_rest_of_patch = TRUE;
  259.             }
  260.             else {
  261.                 ask3(
  262. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  263.                 reverse ? "R" : "Unr",
  264.                 reverse ? "Assume" : "Ignore");
  265.                 if (*buf == 'n') {
  266.                 ask1("Apply anyway? [n] ");
  267.                 if (*buf != 'y')
  268.                     skip_rest_of_patch = TRUE;
  269.                 where = Nulline;
  270.                 reverse = !reverse;
  271.                 if (!pch_swap())  /* put it back to normal */
  272.                     fatal1("Lost hunk on alloc error!\n");
  273.                 }
  274.             }
  275.             }
  276.         } while (!skip_rest_of_patch && where == Nulline &&
  277.             ++fuzz <= mymaxfuzz);
  278.  
  279.         if (skip_rest_of_patch) {               /* just got decided */
  280.             Fclose(ofp);
  281.             ofp = Nullfp;
  282.         }
  283.         }
  284.  
  285.         newwhere = pch_newfirst() + last_offset;
  286.         if (skip_rest_of_patch) {
  287.         abort_hunk();
  288.         failed++;
  289.         if (verbose)
  290.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  291.         }
  292.         else if (where == Nulline) {
  293.         abort_hunk();
  294.         failed++;
  295.         if (verbose)
  296.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  297.         }
  298.         else {
  299.         apply_hunk(where);
  300.         if (verbose) {
  301.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  302.             if (fuzz)
  303.             say2(" with fuzz %ld", fuzz);
  304.             if (last_offset)
  305.             say3(" (offset %ld line%s)",
  306.                 last_offset, last_offset==1L?"":"s");
  307.             say1(".\n");
  308.         }
  309.         }
  310.     }
  311.  
  312.     if (out_of_mem && using_plan_a) {
  313.         Argc = Argc_last;
  314.         Argv = Argv_last;
  315.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  316.         continue;
  317.     }
  318.  
  319.     assert(hunk);
  320.  
  321.     /* finish spewing out the new file */
  322.     if (!skip_rest_of_patch)
  323.         spew_output();
  324.  
  325.     /* and put the output where desired */
  326.     ignore_signals();
  327.     if (!skip_rest_of_patch) {
  328.         if (move_file(TMPOUTNAME, outname) < 0) {
  329.         toutkeep = TRUE;
  330.         chmod(TMPOUTNAME, filemode);
  331.         }
  332.         else
  333.         chmod(outname, filemode);
  334.     }
  335.     Fclose(rejfp);
  336.     rejfp = Nullfp;
  337.     if (failed) {
  338.         failtotal += failed;
  339.         if (!*rejname) {
  340.         Strcpy(rejname, outname);
  341. #ifndef FLEXFILENAMES
  342.         {
  343.             char *rindex();
  344.             char *s = rindex(rejname,'/');
  345.  
  346.             if (!s)
  347.             s = rejname;
  348.             if (strlen(s) > 13)
  349.             if (s[12] == '.')       /* try to preserve difference */
  350.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  351.             s[13] = '\0';
  352.         }
  353. #endif
  354.         Strcat(rejname, REJEXT);
  355.         }
  356.         if (skip_rest_of_patch) {
  357.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  358.             failed, hunk, rejname);
  359.         }
  360.         else {
  361.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  362.             failed, hunk, rejname);
  363.         }
  364.         if (move_file(TMPREJNAME, rejname) < 0)
  365.         trejkeep = TRUE;
  366.     }
  367.     set_signals(1);
  368.     }
  369.     my_exit(failtotal);
  370. }
  371.  
  372. /* Prepare to find the next patch to do in the patch file. */
  373.  
  374. void
  375. reinitialize_almost_everything()
  376. {
  377.     re_patch();
  378.     re_input();
  379.  
  380.     input_lines = 0;
  381.     last_frozen_line = 0;
  382.  
  383.     filec = 0;
  384.     if (filearg[0] != Nullch && !out_of_mem) {
  385.     free(filearg[0]);
  386.     filearg[0] = Nullch;
  387.     }
  388.  
  389.     if (outname != Nullch) {
  390.     free(outname);
  391.     outname = Nullch;
  392.     }
  393.  
  394.     last_offset = 0;
  395.  
  396.     diff_type = 0;
  397.  
  398.     if (revision != Nullch) {
  399.     free(revision);
  400.     revision = Nullch;
  401.     }
  402.  
  403.     reverse = reverse_flag_specified;
  404.     skip_rest_of_patch = FALSE;
  405.  
  406.     get_some_switches();
  407.  
  408.     if (filec >= 2)
  409.     fatal1("You may not change to a different patch file.\n");
  410. }
  411.  
  412. static char *
  413. nextarg()
  414. {
  415.     if (!--Argc)
  416.     fatal2("patch: missing argument after `%s'\n", *Argv);
  417.     return *++Argv;
  418. }
  419.  
  420. /* Process switches and filenames up to next '+' or end of list. */
  421.  
  422. void
  423. get_some_switches()
  424. {
  425.     Reg1 char *s;
  426.  
  427.     rejname[0] = '\0';
  428.     Argc_last = Argc;
  429.     Argv_last = Argv;
  430.     if (!Argc)
  431.     return;
  432.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  433.     s = Argv[0];
  434.     if (strEQ(s, "+")) {
  435.         return;            /* + will be skipped by for loop */
  436.     }
  437.     if (*s != '-' || !s[1]) {
  438.         if (filec == MAXFILEC)
  439.         fatal1("patch: Too many file arguments.\n");
  440.         filearg[filec++] = savestr(s);
  441.     }
  442.     else {
  443.         switch (*++s) {
  444.         case 'b':
  445.         origext = savestr(nextarg());
  446.         break;
  447.         case 'B':
  448.         origprae = savestr(nextarg());
  449.         break;
  450.         case 'c':
  451.         diff_type = CONTEXT_DIFF;
  452.         break;
  453.         case 'd':
  454.         if (!*++s)
  455.             s = nextarg();
  456.         if (chdir(s) < 0)
  457.             fatal2("Can't cd to %s.\n", s);
  458.         break;
  459.         case 'D':
  460.         do_defines = TRUE;
  461.         if (!*++s)
  462.             s = nextarg();
  463.         if (!isalpha(*s) && '_' != *s)
  464.             fatal1("Argument to -D not an identifier.\n");
  465.         Sprintf(if_defined, "#ifdef %s\n", s);
  466.         Sprintf(not_defined, "#ifndef %s\n", s);
  467.         Sprintf(end_defined, "#endif /* %s */\n", s);
  468.         break;
  469.         case 'e':
  470.         diff_type = ED_DIFF;
  471.         break;
  472.         case 'f':
  473.         force = TRUE;
  474.         break;
  475.         case 'F':
  476.         if (*++s == '=')
  477.             s++;
  478.         maxfuzz = atoi(s);
  479.         break;
  480.         case 'l':
  481.         canonicalize = TRUE;
  482.         break;
  483.         case 'n':
  484.         diff_type = NORMAL_DIFF;
  485.         break;
  486.         case 'N':
  487.         noreverse = TRUE;
  488.         break;
  489.         case 'o':
  490.         outname = savestr(nextarg());
  491.         break;
  492.         case 'p':
  493.         if (*++s == '=')
  494.             s++;
  495.         strippath = atoi(s);
  496.         break;
  497.         case 'r':
  498.         Strcpy(rejname, nextarg());
  499.         break;
  500.         case 'R':
  501.         reverse = TRUE;
  502.         reverse_flag_specified = TRUE;
  503.         break;
  504.         case 's':
  505.         verbose = FALSE;
  506.         break;
  507.         case 'S':
  508.         skip_rest_of_patch = TRUE;
  509.         break;
  510.         case 'u':
  511.         diff_type = UNI_DIFF;
  512.         break;
  513.         case 'v':
  514.         version();
  515.         break;
  516. #ifdef DEBUGGING
  517.         case 'x':
  518.         debug = atoi(s+1);
  519.         break;
  520. #endif
  521.         default:
  522.         fprintf(stderr, "patch: unrecognized option `%s'\n", Argv[0]);
  523.         fprintf(stderr, "\
  524. Usage: patch [-ceflnNRsSuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
  525.        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
  526.        [-r rej-name] [origfile] [patchfile] [[+] [options] [origfile]...]\n\
  527. ");
  528.         my_exit(1);
  529.         }
  530.     }
  531.     }
  532. }
  533.  
  534. /* Attempt to find the right place to apply this hunk of patch. */
  535.  
  536. LINENUM
  537. locate_hunk(fuzz)
  538. LINENUM fuzz;
  539. {
  540.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  541.     Reg2 LINENUM offset;
  542.     LINENUM pat_lines = pch_ptrn_lines();
  543.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  544.                 - pat_lines + 1;
  545.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  546.                 + pch_context();
  547.  
  548.     if (!pat_lines)                     /* null range matches always */
  549.     return first_guess;
  550.     if (max_neg_offset >= first_guess)  /* do not try lines < 0 */
  551.     max_neg_offset = first_guess - 1;
  552.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  553.     return first_guess;
  554.     for (offset = 1; ; offset++) {
  555.     Reg5 bool check_after = (offset <= max_pos_offset);
  556.     Reg6 bool check_before = (offset <= max_neg_offset);
  557.  
  558.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  559. #ifdef DEBUGGING
  560.         if (debug & 1)
  561.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  562. #endif
  563.         last_offset = offset;
  564.         return first_guess+offset;
  565.     }
  566.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  567. #ifdef DEBUGGING
  568.         if (debug & 1)
  569.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  570. #endif
  571.         last_offset = -offset;
  572.         return first_guess-offset;
  573.     }
  574.     else if (!check_before && !check_after)
  575.         return Nulline;
  576.     }
  577. }
  578.  
  579. /* We did not find the pattern, dump out the hunk so they can handle it. */
  580.  
  581. void
  582. abort_hunk()
  583. {
  584.     Reg1 LINENUM i;
  585.     Reg2 LINENUM pat_end = pch_end();
  586.     /* add in last_offset to guess the same as the previous successful hunk */
  587.     LINENUM oldfirst = pch_first() + last_offset;
  588.     LINENUM newfirst = pch_newfirst() + last_offset;
  589.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  590.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  591.     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
  592.     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
  593.  
  594.     fprintf(rejfp, "***************\n");
  595.     for (i=0; i<=pat_end; i++) {
  596.     switch (pch_char(i)) {
  597.     case '*':
  598.         if (oldlast < oldfirst)
  599.         fprintf(rejfp, "*** 0%s\n", stars);
  600.         else if (oldlast == oldfirst)
  601.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  602.         else
  603.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  604.         break;
  605.     case '=':
  606.         if (newlast < newfirst)
  607.         fprintf(rejfp, "--- 0%s\n", minuses);
  608.         else if (newlast == newfirst)
  609.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  610.         else
  611.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  612.         break;
  613.     case '\n':
  614.         fprintf(rejfp, "%s", pfetch(i));
  615.         break;
  616.     case ' ': case '-': case '+': case '!':
  617.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  618.         break;
  619.     default:
  620.         say1("Fatal internal error in abort_hunk().\n");
  621.         abort();
  622.     }
  623.     }
  624. }
  625.  
  626. /* We found where to apply it (we hope), so do it. */
  627.  
  628. void
  629. apply_hunk(where)
  630. LINENUM where;
  631. {
  632.     Reg1 LINENUM old = 1;
  633.     Reg2 LINENUM lastline = pch_ptrn_lines();
  634.     Reg3 LINENUM new = lastline+1;
  635. #define OUTSIDE 0
  636. #define IN_IFNDEF 1
  637. #define IN_IFDEF 2
  638. #define IN_ELSE 3
  639.     Reg4 int def_state = OUTSIDE;
  640.     Reg5 bool R_do_defines = do_defines;
  641.     Reg6 LINENUM pat_end = pch_end();
  642.  
  643.     where--;
  644.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  645.     new++;
  646.  
  647.     while (old <= lastline) {
  648.     if (pch_char(old) == '-') {
  649.         copy_till(where + old - 1);
  650.         if (R_do_defines) {
  651.         if (def_state == OUTSIDE) {
  652.             fputs(not_defined, ofp);
  653.             def_state = IN_IFNDEF;
  654.         }
  655.         else if (def_state == IN_IFDEF) {
  656.             fputs(else_defined, ofp);
  657.             def_state = IN_ELSE;
  658.         }
  659.         fputs(pfetch(old), ofp);
  660.         }
  661.         last_frozen_line++;
  662.         old++;
  663.     }
  664.     else if (new > pat_end) {
  665.         break;
  666.     }
  667.     else if (pch_char(new) == '+') {
  668.         copy_till(where + old - 1);
  669.         if (R_do_defines) {
  670.         if (def_state == IN_IFNDEF) {
  671.             fputs(else_defined, ofp);
  672.             def_state = IN_ELSE;
  673.         }
  674.         else if (def_state == OUTSIDE) {
  675.             fputs(if_defined, ofp);
  676.             def_state = IN_IFDEF;
  677.         }
  678.         }
  679.         fputs(pfetch(new), ofp);
  680.         new++;
  681.     }
  682.     else if (pch_char(new) != pch_char(old)) {
  683.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  684.         pch_hunk_beg() + old,
  685.         pch_hunk_beg() + new);
  686. #ifdef DEBUGGING
  687.         say3("oldchar = '%c', newchar = '%c'\n",
  688.         pch_char(old), pch_char(new));
  689. #endif
  690.         my_exit(1);
  691.     }
  692.     else if (pch_char(new) == '!') {
  693.         copy_till(where + old - 1);
  694.         if (R_do_defines) {
  695.            fputs(not_defined, ofp);
  696.            def_state = IN_IFNDEF;
  697.         }
  698.         while (pch_char(old) == '!') {
  699.         if (R_do_defines) {
  700.             fputs(pfetch(old), ofp);
  701.         }
  702.         last_frozen_line++;
  703.         old++;
  704.         }
  705.         if (R_do_defines) {
  706.         fputs(else_defined, ofp);
  707.         def_state = IN_ELSE;
  708.         }
  709.         while (pch_char(new) == '!') {
  710.         fputs(pfetch(new), ofp);
  711.         new++;
  712.         }
  713.     }
  714.     else {
  715.         assert(pch_char(new) == ' ');
  716.         old++;
  717.         new++;
  718.         if (R_do_defines && def_state != OUTSIDE) {
  719.         fputs(end_defined, ofp);
  720.         def_state = OUTSIDE;
  721.         }
  722.     }
  723.     }
  724.     if (new <= pat_end && pch_char(new) == '+') {
  725.     copy_till(where + old - 1);
  726.     if (R_do_defines) {
  727.         if (def_state == OUTSIDE) {
  728.         fputs(if_defined, ofp);
  729.         def_state = IN_IFDEF;
  730.         }
  731.         else if (def_state == IN_IFNDEF) {
  732.         fputs(else_defined, ofp);
  733.         def_state = IN_ELSE;
  734.         }
  735.     }
  736.     while (new <= pat_end && pch_char(new) == '+') {
  737.         fputs(pfetch(new), ofp);
  738.         new++;
  739.     }
  740.     }
  741.     if (R_do_defines && def_state != OUTSIDE) {
  742.     fputs(end_defined, ofp);
  743.     }
  744. }
  745.  
  746. /* Open the new file. */
  747.  
  748. void
  749. init_output(name)
  750. char *name;
  751. {
  752.     ofp = fopen(name, "w");
  753.     if (ofp == Nullfp)
  754.     fatal2("patch: can't create %s.\n", name);
  755. }
  756.  
  757. /* Open a file to put hunks we can't locate. */
  758.  
  759. void
  760. init_reject(name)
  761. char *name;
  762. {
  763.     rejfp = fopen(name, "w");
  764.     if (rejfp == Nullfp)
  765.     fatal2("patch: can't create %s.\n", name);
  766. }
  767.  
  768. /* Copy input file to output, up to wherever hunk is to be applied. */
  769.  
  770. void
  771. copy_till(lastline)
  772. Reg1 LINENUM lastline;
  773. {
  774.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  775.  
  776.     if (R_last_frozen_line > lastline)
  777.     say1("patch: misordered hunks! output will be garbled.\n");
  778.     while (R_last_frozen_line < lastline) {
  779.     dump_line(++R_last_frozen_line);
  780.     }
  781.     last_frozen_line = R_last_frozen_line;
  782. }
  783.  
  784. /* Finish copying the input file to the output file. */
  785.  
  786. void
  787. spew_output()
  788. {
  789. #ifdef DEBUGGING
  790.     if (debug & 256)
  791.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  792. #endif
  793.     if (input_lines)
  794.     copy_till(input_lines);         /* dump remainder of file */
  795.     Fclose(ofp);
  796.     ofp = Nullfp;
  797. }
  798.  
  799. /* Copy one line from input to output. */
  800.  
  801. void
  802. dump_line(line)
  803. LINENUM line;
  804. {
  805.     Reg1 char *s;
  806.     Reg2 char R_newline = '\n';
  807.  
  808.     fflush(stderr);
  809.     /* Note: string is not null terminated. */
  810.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  811. }
  812.  
  813. /* Does the patch pattern match at line base+offset? */
  814.  
  815. bool
  816. patch_match(base, offset, fuzz)
  817. LINENUM base;
  818. LINENUM offset;
  819. LINENUM fuzz;
  820. {
  821.     Reg1 LINENUM pline = 1 + fuzz;
  822.     Reg2 LINENUM iline;
  823.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  824.  
  825.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  826.     if (canonicalize) {
  827.         if (!similar(ifetch(iline, (offset >= 0)),
  828.              pfetch(pline),
  829.              pch_line_len(pline) ))
  830.         return FALSE;
  831.     }
  832.     else if (strnNE(ifetch(iline, (offset >= 0)),
  833.            pfetch(pline),
  834.            pch_line_len(pline) ))
  835.         return FALSE;
  836.     }
  837.     return TRUE;
  838. }
  839.  
  840. /* Do two lines match with canonicalized white space? */
  841.  
  842. bool
  843. similar(a,b,len)
  844. Reg1 char *a;
  845. Reg2 char *b;
  846. Reg3 int len;
  847. {
  848.     while (len) {
  849.     if (isspace(*b)) {              /* whitespace (or \n) to match? */
  850.         if (!isspace(*a))           /* no corresponding whitespace? */
  851.         return FALSE;
  852.         while (len && isspace(*b) && *b != '\n')
  853.         b++,len--;        /* skip pattern whitespace */
  854.         while (isspace(*a) && *a != '\n')
  855.         a++;            /* skip target whitespace */
  856.         if (*a == '\n' || *b == '\n')
  857.         return (*a == *b);      /* should end in sync */
  858.     }
  859.     else if (*a++ != *b++)          /* match non-whitespace chars */
  860.         return FALSE;
  861.     else
  862.         len--;            /* probably not necessary */
  863.     }
  864.     return TRUE;            /* actually, this is not reached */
  865.                     /* since there is always a \n */
  866. }
  867.  
  868. /* Exit with cleanup. */
  869.  
  870. void
  871. my_exit(status)
  872. int status;
  873. {
  874.     Unlink(TMPINNAME);
  875.     if (!toutkeep) {
  876.     Unlink(TMPOUTNAME);
  877.     }
  878.     if (!trejkeep) {
  879.     Unlink(TMPREJNAME);
  880.     }
  881.     Unlink(TMPPATNAME);
  882.     exit(status);
  883. }
  884.